import React from 'react';
import styles from './index.less';
import { Spin, Space, Button, DatePicker, Select, message } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { DownSquareOutlined, UpSquareOutlined, UploadOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import { PageLoading } from '@/components';
import { export_json_to_excel } from '@/utils/fileExport';
import { useTRState, TjChart, TjTable } from '@/pages/ETrade/components';
import { getTreeByCodes } from '@/utils';

import { queryMarketList, provinceSpotClearing, useNewServers } from './services';
import { fmtDataSource, COL_WIDTH } from './helper';
import ImportBtn from './components/ImportBtn';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-7, 'day'), moment().add(-1, 'day')];
};

const ProvinceSpotClearing = (props) => {
  /** data */
  const { menuCode, buttonPermissions } = props;
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === 'provinceSpotClearingExport'),
    canImport: buttonPermissions.some(
      (item) => item.menuCode === 'importGansuClearingPriceSurveillance',
    ),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 表单
    formValues: {},
    loading: true,
    regionItem: null,
    stationItem: null,
    dates: getDateRange(),
    // 数据
    stations: [], // 已选省的所有场站
    resultMap: null,
    chartOption: null,
    tableColumns: [],
    tableData: [],
    // 交互
    isUpSquare: true, // 是否展开,
    featchParams: null,
  });
  const { theme } = useThemeChange();

  React.useEffect(() => {
    init();
  }, []);

  React.useEffect(() => {
    if (state.featchParams && state.resultMap) {
      setTimeout(() => {
        const { chartOption } = fmtDataSource(state.resultMap, state.featchParams);

        setState({
          chartOption,
        });
      }, 1);
    }
  }, [theme]);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
    if (power?.[0]) {
      onChangeRegion(power[0]);
      _onFinish();
    }
  };

  const featchData = async (params) => {
    if (!params.stationId) return;
    setState({ formValues: params, loading: true });
    const res = await provinceSpotClearing(params);

    if (res.statusCode !== HttpCode.SUCCESS) {
      setState({
        resultMap: null,
        tableData: [],
        loading: false,
      });
      message.warning(res.message);
    } else {
      let resultMap = _.get(res, 'resultMap', null);
      if (useNewServers.includes(params.marketId)) {
        resultMap = _.get(res, 'data.resultMap', null);
      }
      setState({
        resultMap,
        ...fmtDataSource(resultMap, params),
        featchParams: params,
        loading: false,
      });
    }
  };

  /** methods */
  const onChangeRegion = (regionItem) => {
    // 切换省份
    const stations = _.flatten((regionItem?.children || []).map((x) => x.children));
    const stationItem = stations?.[0] || null;
    // 防止setState异步
    state.stationItem = stationItem;
    state.regionItem = regionItem;
    setState({
      stations,
      stationItem,
      regionItem,
    });
  };

  const _onFinish = () => {
    // 提交查询表单
    const { regionItem, stationItem, dates } = state;
    let params = {
      provinceId: regionItem?.provinceId || '',
      stationId: stationItem?.stationId || '',
      startDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
      // marketId: stationItem.marketId,
    };

    if (useNewServers.includes(stationItem.marketId)) {
      params['marketId'] = stationItem.marketId;
      delete params.provinceId;
    }
    featchData(params);
  };

  const _onReset = () => {
    const dates = getDateRange();
    state.dates = dates;
    setState({
      dates,
    });
    onChangeRegion(state.power?.[0]);
    _onFinish();
  };

  // 导出数据
  const _onExport = () => {
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    const filename = `现货出清结果`;
    const header = state.tableColumns.map(({ name }) => name);
    const data = state.tableData.map((row) => state.tableColumns.map(({ code }) => row[code]));
    export_json_to_excel({
      filename,
      header,
      data,
    });
  };

  /** render */
  const _renderForm = () => {
    return (
      <Space size={16} wrap>
        <Select
          style={{ width: 200 }}
          value={state.regionItem?.value}
          options={state.power}
          optionFilterProp="label"
          showSearch
          showArrow
          onChange={(v, opt) => onChangeRegion(opt)}
        />
        <Select
          style={{ width: 200 }}
          value={state.stationItem?.value}
          options={state.stations}
          optionFilterProp="label"
          showSearch
          showArrow
          onChange={(v, stationItem) => setState({ stationItem })}
        />
        <DatePicker.RangePicker
          style={{ width: 256 }}
          value={state.dates}
          separator="-"
          format={'YYYYMMDD'}
          allowClear={false}
          onChange={(dates) => setState({ dates })}
        />
        <Space size={16}>
          <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
            查询
          </Button>
          <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
            重置
          </Button>
        </Space>
      </Space>
    );
  };

  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.stations?.length) return <TRDefault type="lock" />;
    if (!state.resultMap) return <TRDefault type="empty" />;
    return (
      <div className={styles.flexcolumn}>
        <div className={styles.title}>出清电力/电价</div>
        <div className={styles.chart}>
          <TjChart option={state.chartOption} />
        </div>
        <div className={styles.table}>
          <Button
            className={styles.squareBtn}
            style={{ padding: 0 }}
            type="link"
            icon={state.isUpSquare ? <UpSquareOutlined /> : <DownSquareOutlined />}
            onClick={() => setState({ isUpSquare: !state.isUpSquare })}
          >
            {state.isUpSquare ? '收起' : '展开'}
          </Button>
          {state.isUpSquare && (
            <TjTable
              columns={state.tableColumns}
              dataSource={state.tableData}
              useVirtual={{ horizontal: true, vertical: false, header: true }}
              defaultColumnWidth={COL_WIDTH}
            />
          )}
        </div>
      </div>
    );
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  const { formValues, canImport } = state;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.content}>
        <div className={styles.head}>
          <div>{_renderForm()}</div>
          <Space size={16} wrap>
            {formValues?.provinceId == '62' && (
              <ImportBtn
                disabled={!canImport}
                stationId={formValues?.stationId}
                provinceId={formValues?.provinceId}
              />
            )}
            <Button
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          <div className={styles.box}>{_renderMain()}</div>
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ProvinceSpotClearing);
